package com.fs.sys.web;

import com.fs.sys.bean.dto.AppCategoryDTO;
import com.fs.sys.bean.query.AppCategoryQuery;
import com.fs.sys.entityservice.AppCategoryEntityService;
import com.fs.common.AppConstants;
import com.fs.common.annotations.Log;
import com.fs.common.bean.LogType;
import com.fs.common.bean.UserContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 应用分类控制器 
 * @author Coder Generator 2025-06-06 11:03:02 
 **/
@RestController
@RequestMapping("/sys/app-category")
@Slf4j
@Tag(name = "应用分类控制器")
public class AppCategoryController {
    @Autowired
    private AppCategoryEntityService service;

    @PostMapping("add")
    @Operation(summary = "新增")
    @Log(value = "应用分类", op = LogType.NEW)
    public void add(@RequestBody @Validated AppCategoryDTO req) {
        service.insert(req);
    }

    @PutMapping("update")
    @Operation(summary = "更新")
    @Log(value = "应用分类", op = LogType.EDIT)
    public void update(@RequestBody @Validated AppCategoryDTO req) {
        service.update(req);
    }

    @DeleteMapping("delete/{id}")
    @Operation(summary = "删除")
    @Log(value = "应用分类", op = LogType.DELETE)
    public void delete(@PathVariable("id") String id) {
        service.delete(id);
    }

    @GetMapping("detail/{id}")
    @Operation(summary = "根据id查找记录")
    public AppCategoryDTO findById(@PathVariable("id") String id) {
        return service.findById(id).orElse(null);
    }

    @PostMapping("query")
    @Operation(summary = "查询-不分页")
    public List<AppCategoryDTO> query(@RequestBody AppCategoryQuery query) {
        String currentTenantId = UserContextHolder.getTenantIdOrThrow();
        return service.query(query)
                .stream().filter(item -> {
                    // 过滤掉非本身及超级租户的分类
                    String tenantId = item.getTenantId();
                    return tenantId.equals(AppConstants.SUPER_TENANT) || tenantId.equals(currentTenantId);
                }).toList();
    }

    @GetMapping("tree")
    public List<AppCategoryDTO> tree() {
        String currentTenantId = UserContextHolder.getTenantIdOrThrow();
        return service.findAll("sort", true)
                .stream().filter(item -> {
                    // 过滤掉非本身及超级租户的分类
                    String tenantId = item.getTenantId();
                    return tenantId.equals(AppConstants.SUPER_TENANT) || tenantId.equals(currentTenantId);
                })
                .peek(item -> item.setReadonly(!item.getTenantId().equals(currentTenantId)))
                .toList();
    }
}